// src/store/slices/translateSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import aiService from '../../services/aiService';
import { Translation } from '../../types';

interface TranslateState {
  sourceText: string;
  translatedText: string;
  sourceLang: string;
  targetLang: string;
  detectedLang: string | null;
  history: Translation[];
  favorites: Translation[];
  isTranslating: boolean;
  error: string | null;
  usageToday: number;
  usageLimit: number;
}

const initialState: TranslateState = {
  sourceText: '',
  translatedText: '',
  sourceLang: 'auto',
  targetLang: 'en',
  detectedLang: null,
  history: [],
  favorites: [],
  isTranslating: false,
  error: null,
  usageToday: 0,
  usageLimit: 20,
};

// 异步actions
export const translate = createAsyncThunk(
  'translate/translate',
  async ({ text, sourceLang, targetLang }: {
    text: string;
    sourceLang: string;
    targetLang: string;
  }) => {
    const response = await aiService.translate({
      text,
      sourceLang,
      targetLang,
    });
    return response;
  }
);

export const batchTranslate = createAsyncThunk(
  'translate/batchTranslate',
  async ({ texts, sourceLang, targetLang }: {
    texts: string[];
    sourceLang: string;
    targetLang: string;
  }) => {
    const response = await aiService.batchTranslate(texts, sourceLang, targetLang);
    return response;
  }
);

export const loadTranslationHistory = createAsyncThunk(
  'translate/loadHistory',
  async ({ page = 1 }: { page?: number } = {}) => {
    const response = await aiService.getTranslationHistory(page);
    return response;
  }
);

const translateSlice = createSlice({
  name: 'translate',
  initialState,
  reducers: {
    setSourceText: (state, action: PayloadAction<string>) => {
      state.sourceText = action.payload;
    },
    setTranslatedText: (state, action: PayloadAction<string>) => {
      state.translatedText = action.payload;
    },
    setSourceLang: (state, action: PayloadAction<string>) => {
      state.sourceLang = action.payload;
    },
    setTargetLang: (state, action: PayloadAction<string>) => {
      state.targetLang = action.payload;
    },
    swapLanguages: (state) => {
      if (state.sourceLang !== 'auto') {
        const temp = state.sourceLang;
        state.sourceLang = state.targetLang;
        state.targetLang = temp;

        const tempText = state.sourceText;
        state.sourceText = state.translatedText;
        state.translatedText = tempText;
      }
    },
    addToHistory: (state, action: PayloadAction<Translation>) => {
      state.history.unshift(action.payload);
      if (state.history.length > 100) {
        state.history.pop();
      }
    },
    addToFavorites: (state, action: PayloadAction<Translation>) => {
      const exists = state.favorites.find((f) => f.id === action.payload.id);
      if (!exists) {
        state.favorites.push(action.payload);
      }
    },
    removeFromFavorites: (state, action: PayloadAction<string>) => {
      state.favorites = state.favorites.filter((f) => f.id !== action.payload);
    },
    clearHistory: (state) => {
      state.history = [];
    },
    clearError: (state) => {
      state.error = null;
    },
    resetTranslate: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Translate
      .addCase(translate.pending, (state) => {
        state.isTranslating = true;
        state.error = null;
      })
      .addCase(translate.fulfilled, (state, action) => {
        state.isTranslating = false;
        state.translatedText = action.payload.translatedText;
        state.detectedLang = action.payload.detectedLanguage || null;
        state.usageToday += 1;

        // 添加到历史
        const translation: Translation = {
          id: Date.now().toString(),
          sourceText: state.sourceText,
          translatedText: action.payload.translatedText,
          sourceLang: state.sourceLang === 'auto'
            ? (action.payload.detectedLanguage || state.sourceLang)
            : state.sourceLang,
          targetLang: state.targetLang,
          timestamp: new Date(),
        };
        state.history.unshift(translation);
      })
      .addCase(translate.rejected, (state, action) => {
        state.isTranslating = false;
        state.error = action.error.message || '翻译失败';
      })
      // Load History
      .addCase(loadTranslationHistory.fulfilled, (state, action) => {
        state.history = action.payload.translations;
      });
  },
});

export const {
  setSourceText,
  setTranslatedText,
  setSourceLang,
  setTargetLang,
  swapLanguages,
  addToHistory,
  addToFavorites,
  removeFromFavorites,
  clearHistory,
  clearError,
  resetTranslate,
} = translateSlice.actions;

export default translateSlice.reducer;